
package com.hangzhou.xyj.utils;

import android.content.Context;
import android.text.TextUtils;
import android.text.format.DateUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Pattern;

/**
 * @author : neo.duan
 * @date : 2015/7/7
 * 字符串工具类
 */
public class StringUtil {
	
	
	private static final SimpleDateFormat ISO_8601_DATE_TIME_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
	private static final SimpleDateFormat ISO_8601_BASE = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss", Locale.US);
	private static final Pattern ISO_8601_EXTRAS = Pattern
			.compile("^(\\.\\d+)?(?:Z|([+-])(\\d{2}):(\\d{2}))?$");
	static {
		ISO_8601_DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
		ISO_8601_BASE.setTimeZone(TimeZone.getTimeZone("UTC"));
	}
	
	
	/**
	   * Formats the date and time based on user's phone date/time preferences.
	   * 
	   * @param context the context
	   * @param time the time in milliseconds
	   */
	  public static String formatDateTime(Context context, long time) {
	    return DateUtils.formatDateTime(
	        context, time, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE) + " "
	        + DateUtils.formatDateTime(context, time, DateUtils.FORMAT_SHOW_TIME).toString();
	  }

	  /**
	   * Formats the time using the ISO 8601 date time format with fractional
	   * seconds in UTC time zone.
	   * 
	   * @param time the time in milliseconds
	   */
	  public static String formatDateTimeIso8601(long time) {
	    return ISO_8601_DATE_TIME_FORMAT.format(time);
	  }

	  /**
	   * Formats the elapsed timed in the form "MM:SS" or "H:MM:SS".
	   * 
	   * @param time the time in milliseconds
	   */
	  public static String formatElapsedTime(long time) {
	    /*
	     * Temporary workaround for DateUtils.formatElapsedTime(time / 1000). In API
	     * level 17, it returns strings like "1:0:00" instead of "1:00:00", which
	     * breaks several unit tests.
	     */
	    if (time < 0) {
	      return "-";
	    }
	    long hours = 0;
	    long minutes = 0;
	    long seconds = 0;
	    long elapsedSeconds = time / 1000;

	    if (elapsedSeconds >= 3600) {
	      hours = elapsedSeconds / 3600;
	      elapsedSeconds -= hours * 3600;
	    }
	    if (elapsedSeconds >= 60) {
	      minutes = elapsedSeconds / 60;
	      elapsedSeconds -= minutes * 60;
	    }
	    seconds = elapsedSeconds;

	    if (hours > 0) {
	      return String.format(Locale.US, "%d:%02d:%02d", hours, minutes, seconds);
	    } else {
	      return String.format(Locale.US, "%02d:%02d", minutes, seconds);
	    }
	  }

	  /**
	   * Formats the elapsed time in the form "H:MM:SS".
	   * 
	   * @param time the time in milliseconds
	   */
	  public static String formatElapsedTimeWithHour(long time) {
	    String value = formatElapsedTime(time);
	    return TextUtils.split(value, ":").length == 2 ? "0:" + value : value;
	  }

	  /**
	   * Formats the given text as a XML CDATA element. This includes adding the
	   * starting and ending CDATA tags. Please notice that this may result in
	   * multiple consecutive CDATA tags.
	   * 
	   * @param text the given text
	   */
	  public static String formatCData(String text) {
	    return "<![CDATA[" + text.replaceAll("]]>", "]]]]><![CDATA[>") + "]]>";
	  }

    /**
     * 半角转全�?
     * 
     * @param half
     * @return 全角字符�?.
     */
    public static String halfToFull(String half) {
        if (isEmpty(half))
            return half;

        char c[] = half.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == ' ') {
                c[i] = '\u3000';
            } else if (c[i] < '\177') {
                c[i] = (char) (c[i] + 65248);
            }
        }

        return new String(c);
    }

    /**
     * 全角转半�?
     * 
     * @param full
     * @return 半角字符�?
     */
    public static String fullToHalf(String full) {
        if (isEmpty(full))
            return full;

        char c[] = full.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == '\u3000') {
                c[i] = ' ';
            } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
                c[i] = (char) (c[i] - 65248);
            }
        }

        String result = new String(c);
        return result;
    }

/**
     * 处理html中的特殊字符�?
     * 
     * <pre>
     * htmlEscapeCharsToString(null) = null;
     * htmlEscapeCharsToString("") = "";
     * htmlEscapeCharsToString("mp3") = "mp3";
     * htmlEscapeCharsToString("mp3&lt;") = "mp3<";
     * htmlEscapeCharsToString("mp3&gt;") = "mp3\>";
     * htmlEscapeCharsToString("mp3&amp;mp4") = "mp3&mp4";
     * htmlEscapeCharsToString("mp3&quot;mp4") = "mp3\"mp4";
     * htmlEscapeCharsToString("mp3&lt;&gt;&amp;&quot;mp4") = "mp3\<\>&\"mp4";
     * </pre>
     * 
     * @param html
     * @return
     */
    public static String htmlEscapeCharsToString(String html) {
        return isEmpty(html) ? html : html.replaceAll("&lt;", "<")
                .replaceAll("&gt;", ">").replaceAll("&amp;", "&")
                .replaceAll("&quot;", "\"");
    }

    /**
     * 将字符串用UTF-8编码，发生异常时，抛出异�?
     * 
     * <pre>
     * utf8Encode(null)        =   null
     * utf8Encode("")          =   "";
     * utf8Encode("aa")        =   "aa";
     * utf8Encode("啊啊啊啊")   = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
     * </pre>
     * 
     * @param str
     * @return
     * @throws
     */
    public static String utf8UrlEncode(String str) {
        return urlEncode(str, "UTF-8");
    }

    /**
     * 将字符串用指定的编码进行编码，发生异常时，抛出异�?
     * 
     * @param str
     * @param charset
     * @return
     */
    public static String urlEncode(String str, String charset) {
        if (!isEmpty(str)) {
            try {
                return URLEncoder.encode(str, charset);
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
                throw new RuntimeException(
                        "UnsupportedEncodingException occurred. ", ex);
            }
        }
        return str;
    }

    /**
     * 字符串是否为�?
     * 
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

    /**
     * 字符串是否为非空
     * 
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return (str != null && str.length() != 0);
    }

    /**
     * 字符串是否为空格�?
     * 
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0 || "null".equals(str));
    }

    /**
     * 字符串是否非空格�?
     * 
     * @param str
     * @return
     */
    public static boolean isNotBlank(String str) {
        return (str != null && str.trim().length() != 0 && !"null".equals(str));
    }

    /**
     * 将null转换为空�?,如果参数为非null，则直接返回
     * 
     * @param str
     * @return
     */
    public static String nullToEmpty(String str) {
        return ((str == null || "null".equals(str)) ? "" : str);
    }

    /**
     * 将null转换为字符串NULL,如果参数为非null，则直接返回
     * 
     * @param str
     * @return
     */
    public static String nullToString(String str) {
        return (str == null ? "NULL" : str);
    }


    /**
     * ellipsise the data at the maxLen
     *
     * @param input  string to check
     * @param maxLen macLen
     * @return handled data
     */
    public static String ellipsise(String input, int maxLen) {
        if (input == null)
            return null;
        if ((input.length() < maxLen) || (maxLen < 3))
            return input;
        return input.substring(0, maxLen - 3) + "...";
    }
    
}
